package com.wenjiang.config.handler;

import com.wenjiang.common.annotation.TokenMallUser;
import com.wenjiang.common.exception.TokenException;
import com.wenjiang.entity.MallUser;
import com.wenjiang.mapper.MallUserMapper;
import com.wenjiang.common.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 把token 转换为 对应参数实体的处理器
 * 省去通过token 从数据库查数据
 */
@Component
public class TokenToMallUserHandler implements HandlerMethodArgumentResolver {


    @Autowired
    MallUserMapper mallUserMapper;

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //判断参数是否有自定义的注解

        if (methodParameter.hasParameterAnnotation(TokenMallUser.class)){
            return true;
        }

        return false;
    }


    // 把注解上的参数 通过token进行赋值

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //判断token是否为空

        String token = nativeWebRequest.getHeader("token");

        if(token==null){
            throw  new TokenException();
        }

        if(JWTUtil.isExpired(token)){
           throw  new TokenException();
        }



        //查询值
        MallUser mallUser = mallUserMapper.selectById(JWTUtil.getUserId(token));


        return mallUser;
    }
}
